package com.sun.designpatternsdemo.observer

import android.os.Bundle
import android.util.Log
import androidx.databinding.DataBindingUtil
import com.sun.designpatternsdemo.base.BaseActivity
import com.sun.designpatternsdemo.R
import com.sun.designpatternsdemo.app.AppConstant
import com.sun.designpatternsdemo.app.EMTagHandler
import com.sun.designpatternsdemo.databinding.ActivityObserverBinding
import com.sun.designpatternsdemo.observer.bean.*

/**
 * 可以看出，使用Java内置的类实现观察者模式，代码非常简洁，
 * 对了addObserver,removeObserver,notifyObservers都已经为我们实现了，
 * 所有可以看出Observable（主题）是一个类，而不是一个接口，
 * 基本上书上都对于Java的如此设计抱有反面的态度，觉得Java内置的观察者模式，
 * 违法了面向接口编程这个原则，但是如果转念想一想，
 * 的确你拿一个主题在这写观察者模式（我们自己的实现），
 * 接口的思想很好，但是如果现在继续添加很多个主题，
 * 每个主题的ddObserver,removeObserver,notifyObservers代码基本都是相同的吧，
 * 接口是无法实现代码复用的，而且也没有办法使用组合的模式实现这三个方法的复用，
 * 所以我觉得这里把这三个方法在类中实现是合理的。
 */
class ObserverActivity : BaseActivity<ActivityObserverBinding>() {
    private var objectFor3D: ObjectFor3D? = null
    private var observerUser1: ObserverUser1? = null
    private var observerUser2: ObserverUser2? = null
    override fun layoutId(): Int  = R.layout.activity_observer

    override fun initView(savedInstanceState: Bundle?) {
        mDataBind = DataBindingUtil.setContentView(this, R.layout.activity_observer)
        title = "观察者模式"
        mDataBind.apply {
            defineTv.text = EMTagHandler.fromHtml(AppConstant.OBSERVER_DEFINE)
            mySelfBt.setOnClickListener {
                Log.e("TAG", "onCreate: 123", )
                objectFor3D = ObjectFor3D()
                objectFor3D?.let {
                    observerUser1 = ObserverUser1(it)
                    observerUser2 = ObserverUser2(it)
                    it.msg = "01610121 的3D号为:127"
                    it.msg = "20161022 的3D号为:000"
                }
            }
            systemBt.setOnClickListener {
                val subjectFor3d = SubjectFor3d()
                val subjectForSSQ = SubjectForSSQ()
                val observer1 = Observer1()
                observer1.registerSubject(subjectFor3d)
                observer1.registerSubject(subjectForSSQ)
                subjectFor3d.msg = "hello 3d'nums : 110 "
                subjectForSSQ.msg = "ssq'nums : 12,13,31,5,4,3 15"
            }
        }
    }
    override fun onStop() {
        super.onStop()
        if (observerUser1 != null){
            objectFor3D?.removeObserver(observerUser1!!)
        }
        if (observerUser2 != null){
            objectFor3D?.removeObserver(observerUser2!!)
        }
        objectFor3D = null
    }
}